﻿#include "EditAddressController.h"

EditAddressController* EditAddressController::create(unsigned int addressId){
	EditAddressController* me=new EditAddressController(addressId);
	if(me&&me->init()){
		me->autorelease();

		return me;
	}else{
		delete me;
		me=nullptr;

		return nullptr;
	}
}

EditAddressController::EditAddressController(unsigned int addressId){
	this->addressId=addressId;
}

EditAddressController::~EditAddressController(){}

void EditAddressController::viewDidLoad(){
	CAView* view=this->getView();
	this->setNavigationBarItem(CANavigationBarItem::create("编辑地址"));
	if(addressId>0){
		sendHttp(view, "/api/appAddress", obj2str("userId=%u&addressId=%u", userId, addressId), CALLBACK_BIND_1(EditAddressController::fillData, this));
	}
	CAScrollView* scrollView=CAScrollView::createWithLayout(DLayoutFill);

	CAView* subview=getSubview();
	subview->addSubview(getLabel("收货人"));
	name=getTextField();
	subview->addSubview(name);
	scrollView->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("手机号码"));
	phone=getTextField();
	subview->addSubview(phone);
	scrollView->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("所在地区"));
	region=getTextField();
	region->onShouldBeginEditing([&]{
		sendHttp(this->getView(), "/api/dept/allAsTree", "", CALLBACK_BIND_1(EditAddressController::addressData, this));

		return false;
	});
	subview->addSubview(region);
	scrollView->addSubview(subview);
	subview=getSubview();
	subview->addSubview(getLabel("详细地址"));
	detailedAddress=getTextField();
	subview->addSubview(detailedAddress);
	scrollView->addSubview(subview);
	subview=getSubview();
	CAButton* btn=CAButton::createWithLayout(DLayout(DHorizontalLayout_W_C(300, 0.5), DVerticalLayout_T_H(40, 100)), CAButton::Type::RoundedRect);
	btn->setTitleFontSize(50);
	btn->setTitleForState(CAControl::State::Normal, "提   交");
	btn->setTitleColorForState(CAControl::State::Normal, CAColor4B::WHITE);
	btn->setBackgroundImageForState(CAControl::State::Normal, CAImage::createWithColor4B(themeColor), true);
	btn->addTarget([=]{
		CSJson::Value paras;
		if(addressId>0){
			url="/api/appAddress/update";
			paras["addressId"]=addressId;
		}
		paras["userId"]=userId;
		paras["name"]=name->getText();
		paras["phone"]=phone->getText();
		paras["areaCode"]=areaCode;
		paras["region"]=region->getText();
		paras["detailedAddress"]=detailedAddress->getText();
		CSJson::FastWriter writer;
		sendHttp(view, url, writer.write(paras), CALLBACK_BIND_1(EditAddressController::submitData, this), CAHttpRequest::Type::Post, true);
	}, CAButton::Event::TouchDown);
	subview->addSubview(btn);
	scrollView->addSubview(subview);

	scrollView->setViewSize(DSize(view->getBounds().size.width, mt+110));
	scrollView->setBounces(false);
	scrollView->setShowsHorizontalScrollIndicator(false);
	view->addSubview(scrollView);
}

void EditAddressController::fillData(const string& data){
	CSJson::Reader reader;
	CSJson::Value value;
	bool flag=reader.parse(data, value);
	if(!flag){
		getAlert(this->getView(), "数据解析异常, 请稍后重试");

		return;
	}
	CSJson::Value datas=value["content"][0];
	addressId=datas["addressId"].asUInt();
	name->setText(datas["name"].asCString());
	phone->setText(datas["phone"].asCString());
	areaCode=atoi(datas["areaCode"].asCString());
	region->setText(datas["region"].asCString());
	detailedAddress->setText(datas["detailedAddress"].asCString());
}

void EditAddressController::addressData(const string& data){
	CSJson::Reader reader;
	CSJson::Value provinceDatas;
	bool flag=reader.parse(data, provinceDatas);
	if(!flag){
		getAlert(this->getView(), "数据解析异常, 请稍后重试");

		return;
	}
	unsigned int III=0;
	if(areaCode==0){
		cityDatas=provinceDatas[0]["children"];
		countyDatas=cityDatas[0]["children"];
		areaCode=countyDatas[0]["id"].asUInt();
		const char* province=provinceDatas[0]["name"].asCString();
		const char* city=cityDatas[0]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		region->setText(obj2str("%s%s%s", province, city, county));
	}else{
		unsigned int provinceCode=areaCode-areaCode%10000;
		unsigned int cityCode=areaCode-areaCode%100;
		for(int i=0, isize=provinceDatas.size(); i<isize; ++i){
			if(provinceCode==provinceDatas[i]["id"].asUInt()){
				cityDatas=provinceDatas[i]["children"];
				for(int j=0, jsize=cityDatas.size(); j<jsize; j++){
					if(cityCode==cityDatas[j]["id"].asUInt()){
						countyDatas=cityDatas[j]["children"];
						for(int k=0, ksize=countyDatas.size(); k<ksize; k++){
							if(areaCode==countyDatas[k]["id"].asUInt()){
								I=i;
								II=j;
								III=k;
								goto RenderView;
							}
						}
					}
				}
			}
		}
	}

RenderView:
	CAView* view=this->getView();
	CAView* subview=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 500)));
	subview->setColor(ccc4(190, 190, 190, 255));
	subview->setZOrder(50);
	view->addSubview(subview);
	CAButton* btn=CAButton::createWithLayout(DLayout(DHorizontalLayout_R_W(0, 120), DVerticalLayout_T_H(0, 100)), CAButton::Type::Custom);
	btn->setTitleForState(CAControl::State::Normal, "确定");
	btn->setTitleFontSize(60);
	btn->setTitleColorForState(CAControl::State::Normal, themeColor);
	btn->addTarget([=]{
		subview->removeAllSubviews();
		view->removeSubview(subview);
	}, CAButton::Event::TouchUpInSide);
	subview->addSubview(btn);
	float width=subview->getBounds().size.width/3;
	//省
	CAPickerView* provinceView=CAPickerView::createWithLayout(DLayout(DHorizontalLayout_L_W(0, width), DVerticalLayout_T_H(100, 400)));
	provinceView->setFontSizeNormal(40);
	provinceView->setBackgroundImage(CAImage::createWithColor4B(ccc4(190, 190, 190, 255)));
	provinceView->onHeightForComponent([](unsigned int component){
		return 80;
	});
	provinceView->onViewForSelected([](unsigned int component, DSize size){
		return CAView::createWithColor(themeColor);
	});
	provinceView->onTitleForRow([=](unsigned int row, unsigned int component){
		return provinceDatas[row]["name"].asCString();
	});
	provinceView->onWidthForComponent([=](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	provinceView->onNumberOfRowsInComponent([=](unsigned int component){
		return provinceDatas.size();
	});
	provinceView->onDidSelectRow([=](unsigned int row, unsigned int component){
		I=row;
		cityDatas=provinceDatas[row]["children"];
		countyDatas=cityDatas[0]["children"];
		areaCode=countyDatas[0]["id"].asUInt();
		const char* province=provinceDatas[row]["name"].asCString();
		const char* city=cityDatas[0]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		region->setText(obj2str("%s%s%s", province, city, county));
		if(cityView!=nullptr){
			cityView->reloadAllComponents();
			countyView->reloadAllComponents();
		}
	});
	subview->addSubview(provinceView);
	if(I>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			provinceView->selectRow(I, 0, true);
		}, "selectProvince", provinceView, 0);
	}
	//市
	cityView=CAPickerView::createWithLayout(DLayout(DHorizontalLayout_W_C(width, 0.5), DVerticalLayout_T_H(100, 400)));
	cityView->setFontSizeNormal(40);
	cityView->setBackgroundImage(CAImage::createWithColor4B(ccc4(190, 190, 190, 255)));
	cityView->onHeightForComponent([](unsigned int component){
		return 80;
	});
	cityView->onViewForSelected([](unsigned int component, DSize size){
		return CAView::createWithColor(themeColor);
	});
	cityView->onTitleForRow([=](unsigned int row, unsigned int component){
		return cityDatas[row]["name"].asCString();
	});
	cityView->onWidthForComponent([=](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	cityView->onNumberOfRowsInComponent([=](unsigned int component){
		return cityDatas.size();
	});
	cityView->onDidSelectRow([=](unsigned int row, unsigned int component){
		II=row;
		countyDatas=cityDatas[row]["children"];
		areaCode=countyDatas[0]["id"].asUInt();
		const char* province=provinceDatas[I]["name"].asCString();
		const char* city=cityDatas[row]["name"].asCString();
		const char* county=countyDatas[0]["name"].asCString();
		region->setText(obj2str("%s%s%s", province, city, county));
		if(countyView!=nullptr){
			countyView->reloadAllComponents();
		}
	});
	subview->addSubview(cityView);
	if(II>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			cityView->selectRow(II, 0, true);
		}, "selectCity", cityView, 0);
	}
	//区
	countyView=CAPickerView::createWithLayout(DLayout(DHorizontalLayout_R_W(0, width), DVerticalLayout_T_H(100, 400)));
	countyView->setFontSizeNormal(40);
	countyView->setBackgroundImage(CAImage::createWithColor4B(ccc4(190, 190, 190, 255)));
	countyView->onHeightForComponent([](unsigned int component){
		return 80;
	});
	countyView->onViewForSelected([](unsigned int component, DSize size){
		return CAView::createWithColor(themeColor);
	});
	countyView->onTitleForRow([=](unsigned int row, unsigned int component){
		return countyDatas[row]["name"].asCString();
	});
	countyView->onWidthForComponent([=](unsigned int component){
		return this->getView()->getBounds().size.width;
	});
	countyView->onNumberOfRowsInComponent([=](unsigned int component){
		return countyDatas.size();
	});
	countyView->onDidSelectRow([=](unsigned int row, unsigned int component){
		areaCode=countyDatas[row]["id"].asUInt();
		const char* province=provinceDatas[I]["name"].asCString();
		const char* city=cityDatas[II]["name"].asCString();
		const char* county=countyDatas[row]["name"].asCString();
		region->setText(obj2str("%s%s%s", province, city, county));
	});
	subview->addSubview(countyView);
	if(III>0){
		CAScheduler::getScheduler()->scheduleOnce([=](float interval){
			countyView->selectRow(III, 0, true);
		}, "selectCounty", countyView, 0);
	}
}

void EditAddressController::submitData(const string& data){
	getRootWindow()->popViewControllerAnimated(true);
	//保存成功后再删除刚刚编辑的数据,会直接跳转到编辑页,导致删除功能不可用,需要用以下方式解决
	/*CANavigationController* root=getRootWindow();
	root->popViewControllerAtIndex(root->getViewControllerCount()-1);
	root->replaceViewController(AddressController::create(), true);*/
}